﻿using System;
using System.Web;
using System.Text;
using System.Data.OleDb;
using System.Configuration;

namespace Com.Toook.Common
{
    /// <summary>
    /// OleDb辅助类
    /// </summary>
    public class AccessHelper
    {
        /// <summary>
        /// OleDb数据库默认连接字符串
        /// </summary>
        private static string connectionString = "";

        static AccessHelper()
        {
            string connection = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
            string rootPath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
            connectionString = connection.Replace("#WebRootPath#", rootPath);
        }
        /// <summary>
        /// 获取OleDb数据库连接对象, 默认devDB.db
        /// </summary>
        /// <returns></returns>
        public static OleDbConnection GetConnection()
        {
            OleDbConnection con = new OleDbConnection(connectionString);
            return con;
        }
        /// <summary>
        /// 获取网站根目录路径,后面有\ 如：D:\web\
        /// </summary>
        /// <returns></returns>
        public static string RootPath()
        {
            return System.AppDomain.CurrentDomain.BaseDirectory.ToString();
        }
        /// <summary>
        /// 获取Access数据库文件完整路径。D:\web\abc.mdb
        /// </summary>
        /// <returns></returns>
        public static string RootPathAccess()
        {
            return System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "App_Data\\rss.mdb";
        }
        /// <summary>
        /// 关闭数据库资源
        /// </summary>
        /// <param name="con">数据库连接，没有传null</param>
        /// <param name="reader">OleDbDataReader，没有传null</param>
        public static void CloseDbResource(OleDbConnection con, OleDbDataReader reader)
        {
            if(reader != null)
            {
                try
                {
                    reader.Close();
                }
                catch (Exception ex)
                {
                    LogHelper.Log.Error("OleDbHelper.CloseDbResource reader 错误", ex);
                }
            }
            if(con != null)
            {
                try
                {
                    con.Close();
                }
                catch (Exception ex)
                {
                    LogHelper.Log.Error("OleDbHelper.CloseDbResource con 错误", ex);
                }
            }
        }       
       
    }
}
